import React from "react";
import { connect } from "react-redux";
// import { fetchProducts } from "./productActions";

class ProductList extends React.Component {
 
  componentDidMount() {
    function fakeGetProducts() {
      return new Promise(resolve => {
        // Resolve after a timeout so we can see the loading indicator
        setTimeout(
          () =>
            resolve({
              products: [
                {
                  id: 0,
                  name: "Apple"
                },
                {
                  id: 1,
                  name: "Bananas"
                },
                {
                  id: 2,
                  name: "Strawberries"
                }
              ]
            }),
          1000
        );
      });
    }
    let fetchProductsFailure = error => ({
      type: 'FETCH_PRODUCTS_FAILURE',
      payload: { error }
    });
    let fetchProductsSuccess = products => ({
      type: 'FETCH_PRODUCTS_SUCCESS',
      payload: { products }
    });
    let fetchProductsBegin = () => ({
      type: 'FETCH_PRODUCTS_BEGIN'
    })
    // 主函数
    function fetchProducts() {
      
      return dispatch => {
        dispatch(fetchProductsBegin());
        return fakeGetProducts()
          .then(json => {
            dispatch(fetchProductsSuccess(json.products));
            return json.products;
          })
          .catch(error =>
            dispatch(fetchProductsFailure(error))
          );
      };
    }
   
    this.props.dispatch(fetchProducts());
  }

  render() {
    const { error, loading, products } = this.props;

    if (error) {
      return <div>Error! {error.message}</div>;
    }

    if (loading) {
      return <div>Loading...</div>;
    }

    return (
      <ul>
        {products.map(product => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    );
  }
}

const mapStateToProps = state => ({
  products: state.products.items,
  loading: state.products.loading,
  error: state.products.error
});

export default connect(mapStateToProps)(ProductList);

// 参考:https://blog.csdn.net/qq_34634181/article/details/104077983
// 参考:https://www.jianshu.com/p/51c8eaa9fa2a
// 参考:https://blog.csdn.net/wust_cyl/article/details/84627840
// 参考:https://www.jianshu.com/p/4d0389ace873